package com.sjtuy.galtxtreader.gal;

import android.widget.Toast;

import com.sjtuy.galtxtreader.GalActivity;
import com.sjtuy.galtxtreader.R;
import com.sjtuy.galtxtreader.file.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.sjtuy.galtxtreader.file.utils.file2String;

public class GamingTextProvider implements TextProvider{
    File bookDir;
    File saveFile;
    List<File> chapterFiles;
    int[][] socketCache=new int[11][2];
    String[] currentChapterDialogGroup;
    String currentChapterName;
    GalActivity activity;
    boolean hasSeriousError=false;
    public GamingTextProvider(File dir, GalActivity activity){
        bookDir=dir;
        saveFile = new File(bookDir.getPath()+"/saves");
        this.activity = activity;
        chapterFiles = Arrays.asList(new File(bookDir.getPath()+"/chapters").listFiles());
        if(chapterFiles.size()==0){
            postToastShort(R.string.dialog_provider_error_emptychapterlist);
            encounterSeriousError();
        }
        Collections.sort(chapterFiles, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return Integer.valueOf(o1.getName()).compareTo(Integer.valueOf(o2.getName()));
            }
        });
        if(!saveFile.exists())
            try {
                createNewSave();
                postToastShort(R.string.dialog_provider_notice_createsavefile);
            }catch (Exception e){
                e.printStackTrace();
            }

    }
    public void toNextDialog(){
        if(hasSeriousError)
            return;

        if(socketCache[0][1]==currentChapterDialogGroup.length-1){
            if(socketCache[0][0]==chapterFiles.size()){
                return;
            }
            socketCache[0][0]++;
            socketCache[0][1]=1;
            saveStates();
            loadFrom(0);
            return;
        }
        socketCache[0][1]++;
    }
    public void toPreviousDialog(){
        if(hasSeriousError)
            return;
        if(socketCache[0][1]==1){
            if(socketCache[0][0]==1){
                return;
            }
            socketCache[0][0]--;
            saveStates();
            loadFrom(0);
            socketCache[0][1]=currentChapterDialogGroup.length-1;
            return;
        }
        socketCache[0][1]--;
    }
    public String getCurrentDialog(){
        if(hasSeriousError)
            return null;
        if(socketCache[0][1]>=currentChapterDialogGroup.length){
            socketCache[0][1]=currentChapterDialogGroup.length-1;
            postToastShort("socketcache[0][1]越位");
        }
        return currentChapterDialogGroup[socketCache[0][1]];
    }

    public String getCurrentChapterName(){
        if(hasSeriousError)
            return null;

        return currentChapterName;
    }
    public String getCurrentIndex(){
        if(hasSeriousError)
            return null;

        return ""+socketCache[0][0]+"."+socketCache[0][1];
    }

    @Override
    public String getChapterByIndex(String index) {
        try {
            return utils.file2BufferReader(chapterFiles.get(Integer.valueOf(index.split("\\.")[0])-1)).readLine();
        }catch (Exception e){
            return "Invalid";
        }

    }

    @Override
    public String getDialogByIndex(String index) {

        try {
            File chapterFile=  chapterFiles.get(
                    Integer.valueOf(index.split("\\.")[0])-1);
            return file2String(chapterFile).split("\n")[Integer.valueOf(index.split("\\.")[1])];
        }catch (Exception e){
            return "Invalid";
        }
    }

    @Override
    public String getChapterBySocket(int socket) {
        return getChapterByIndex(""+socketCache[socket][0]+"."+socketCache[socket][1]);
    }

    @Override
    public String getDialogBySocket(int socket) {
        return getDialogByIndex(""+socketCache[socket][0]+"."+socketCache[socket][1]);
    }

    public boolean saveTo(int socket){
        if(hasSeriousError)
            return false;
        if(socket<0||socket>10)
            return false;
        socketCache[socket][0]=socketCache[0][0];
        socketCache[socket][1]=socketCache[0][1];
        saveStates();
        return true;
    }
    public boolean loadFrom(int socket){
        if(hasSeriousError)
            return false;

        loadStates();
        if(socket<0||socket>10)
            return false;
        if(socketCache[socket][0]<1||socketCache[socket][0]>chapterFiles.size())
            return false;
        socketCache[0][0]=socketCache[socket][0];
        socketCache[0][1]=socketCache[socket][1];
        File chapterFile = chapterFiles.get(socketCache[0][0]-1);

        try {
            currentChapterDialogGroup = file2String(chapterFile).split("\n");
            if(socketCache[socket][1]<1||socketCache[socket][1]>currentChapterDialogGroup.length-1)
                return false;
            currentChapterName = currentChapterDialogGroup[0];
            return true;
        }catch (IOException e){
            postToastShort(R.string.dialog_provider_error_ioexception);
            encounterSeriousError();
            return false;
        }

    }

    //写入存储
    private void saveStates(){
        if(hasSeriousError)
            return;

        try {
            FileWriter fw=new FileWriter(saveFile);
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<11;++i){
                sb.append(socketCache[i][0]).append(".").append(socketCache[i][1]).append("\n");
            }
            fw.write(sb.toString());
            fw.close();
        }catch (IOException e){
            postToastShort(R.string.dialog_provider_error_ioexception);
            encounterSeriousError();
        }
    }

    //读取存储
    private void loadStates(){
        if(hasSeriousError)
            return;

        try {
            BufferedReader br = new BufferedReader(new FileReader(saveFile));
            String[] strs;
            for(int i=0;i<11;++i){
                String str=br.readLine();
                strs=str.split("\\.");
                socketCache[i][0]=Integer.valueOf(strs[0]);
                socketCache[i][1]=Integer.valueOf(strs[1]);
            }
        }catch (Exception e){
            postToastShort(R.string.dialog_provider_error_savefiledamaged);
            saveFile.delete();
            createNewSave();
            e.printStackTrace();
        }

    }



    private void createNewSave(){
        try {
            saveFile.createNewFile();
            FileWriter fw=new FileWriter(saveFile);
            fw.write("1.1\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n0.0\n");
            fw.close();
        }catch (IOException e){
            postToastShort(R.string.dialog_provider_error_ioexception);
            encounterSeriousError();
        }

    }
    public void postToastShort(int resId){
        Toast.makeText(activity,resId,Toast.LENGTH_SHORT).show();
    }
    public void postToastShort(String str){
        Toast.makeText(activity,str,Toast.LENGTH_SHORT).show();
    }
    private void encounterSeriousError(){
        hasSeriousError=true;
        activity.finish();
    }

}
